/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName GoogleStageWebView.as
 * @creationDate Aug 8, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.socialize.google
{
	import com.gesturesoft.imultimax.socialize.org.osflash.signals.Signal;
	
	import flash.display.Stage;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.LocationChangeEvent;
	import flash.events.StageOrientationEvent;
	import flash.geom.Rectangle;
	import flash.media.StageWebView;
	
	import mx.core.UIComponent;

	public class GoogleStageWebView extends UIComponent
	{
		private var stageWebView:StageWebView;
		private var myStage:Stage;
		private var __url:String;
		private var __text:String;
		public var __yOffset:int = 0;
		public var __heightOffset:int = 0;
		private var __googleService:GoogleService;
		
		public var locationChangeSignal:Signal = new Signal();
		public var locationChangingSignal:Signal = new Signal();
		public var locationComplete:Signal = new Signal();
		
		public function GoogleStageWebView()
		{
			addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
		}
		
		public function hide():void{
			stageWebView.stage = null;
		}
		
		public function show():void{
			stageWebView.stage = myStage;
		}
		
		public function dispose():void{
			hide();
			stageWebView.dispose();
		}
		
		protected function addedToStageHandler(event:Event):void
		{
			myStage = stage;
			removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
			myStage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE,onOrientationChange);
			measureBox();
			hide();
		}
		
		protected function measureBox():void
		{
			stageWebView = new StageWebView();
			stageWebView.stage = myStage;
			stageWebView.viewPort = new Rectangle(0, yOffset, myStage.fullScreenWidth, myStage.fullScreenHeight - heightOffset);
			stageWebView.addEventListener(ErrorEvent.ERROR, errorHandler);
			stageWebView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, locationChangeHandler);
			stageWebView.addEventListener(LocationChangeEvent.LOCATION_CHANGING, locationChangingHandler);
			stageWebView.addEventListener(Event.COMPLETE, extractAccessToken);
			
			if (__url) {
				stageWebView.loadURL(__url);
			} else if (__text) {
				stageWebView.loadString(__text);
			}
		}
		
		private function extractAccessToken(e:Event):void
		{
			locationComplete.dispatch(e.clone());
			var code:String = getValue('code=', stageWebView.title);
			if (code) {
				closeSWV();
				this.googleService.fetchAccessToken(code);
			}
			
		}
		
		private function closeSWV(event:Event=null):void {
			if (! stageWebView)
				return;
			stageWebView.removeEventListener(Event.COMPLETE, extractAccessToken);
			stageWebView.removeEventListener(LocationChangeEvent.LOCATION_CHANGE, locationChangeHandler);
			stageWebView.removeEventListener(LocationChangeEvent.LOCATION_CHANGING, locationChangingHandler);
			stageWebView.removeEventListener(IOErrorEvent.IO_ERROR, closeSWV);
			stageWebView.removeEventListener(ErrorEvent.ERROR, closeSWV);
		}   
		
		private function getValue(key:String, str:String):String {
			const pattern:RegExp = /[-_a-zA-Z0-9\/.]+/;
			var index:int = str.indexOf(key);
			if (index > -1) {
				var matches:Array = str.substring(index + key.length).match(pattern);
				if (matches.length > 0)
					return matches[0];
			}
			return null;
		}
		
		protected function onOrientationChange(event:StageOrientationEvent):void
		{
			if(stage){
				callLater(resize);
			}
		}
		
		protected function resize():void
		{
			stageWebView.viewPort = new Rectangle(0, yOffset, myStage.fullScreenWidth, myStage.fullScreenHeight - heightOffset);
		}
		
		protected function locationChangeHandler(event:LocationChangeEvent):void
		{
			trace("Change : " + event.location);
			locationChangeSignal.dispatch(event.clone());
		}
		
		protected function locationChangingHandler(event:LocationChangeEvent):void
		{
			trace("Changing : " + event.location);
			locationChangingSignal.dispatch(event.clone());
		}
		
		protected function errorHandler(event:Event):void
		{
			dispatchEvent(event.clone());
		}
		
		protected function serviceErrorHandler(errMessage:String):void
		{
			trace("Error received by GoogleStageWebView: "+errMessage);
		}
		
		protected function userInfoReceivedHandler(userData:Array):void
		{
			trace("userInfoReceivedHandler");
		}
		
		public function get yOffset():Number
		{
			return __yOffset;
		}
		
		public function set yOffset(val:Number):void
		{
			__yOffset = val;
		}
		
		public function get heightOffset():Number
		{
			return __heightOffset;
		}
		
		public function set heightOffset(val:Number):void
		{
			__heightOffset = val;
		}
		
		public function get googleService():GoogleService
		{
			return __googleService;
		}
		
		public function set googleService(val:GoogleService):void
		{
			__googleService = val;
			__googleService.userInfoReceived.addOnce(userInfoReceivedHandler);
		}
		
		public function set url(url:String):void
		{
			__url = url;
			
			if(stageWebView){
				stageWebView.loadURL(url);
			}
		}
		
		public function set text(text:String):void
		{
			__text = text;
			
			if(stageWebView){
				stageWebView.loadString(text);
			}
		}
	}
}